const std = @import("std");

const lv_conf_custom = .{
    .LV_CONF_INCLUDE_SIMPLE = 1,

    //custom lv_conf_kconfig.h
    .CONFIG_LV_USE_BUILTIN_MALLOC = 1,
    .CONFIG_LV_USE_BUILTIN_STRING = 1,
    .CONFIG_LV_USE_BUILTIN_SPRINTF = 1,
    .CONFIG_LV_TXT_ENC_UTF8 = 1,

    //custom lv_conf_internal.h
    .LV_COLOR_DEPTH = 32,
};

pub fn build(b: *std.Build) !void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const lvgl = b.addStaticLibrary(.{
        .name = "lvgl",
        .target = target,
        .optimize = optimize,
    });
    try lvgl.c_macros.append("LV_CONF_KCONFIG_EXTERNAL_INCLUDE=<lv_conf_custom.h>");
    lvgl.addIncludePath(.{ .path = b.pathFromRoot("config") });
    lvgl.addIncludePath(.{ .path = b.pathFromRoot("lvgl") });
    b.installArtifact(lvgl);

    const sources = try getSourceFiles(b);
    lvgl.addCSourceFiles(.{
        .files = sources.items,
        .flags = &.{},
    });

    const config_header = b.addConfigHeader(.{
        .include_path = "lv_conf_custom.h",
    }, lv_conf_custom);
    lvgl.addConfigHeader(config_header);
    lvgl.linkLibC();
}

fn getOptions(b: *std.build.Builder) *std.build.Step.Options {
    var options = b.addOptions();
    options.addOption(bool, "dummy", false);
    return options;
}

fn getSourceFiles(b: *std.Build) !std.ArrayList([]const u8) {
    var sources = std.ArrayList([]const u8).init(b.allocator);
    var rootdir = try b.build_root.handle.openDir("lvgl/src", .{ .iterate = true });
    var walker = try rootdir.walk(b.allocator);
    while (try walker.next()) |entry| {
        const path = entry.path;
        if (entry.kind == .file and path.len > 2 and std.mem.eql(u8, path[path.len - 2 ..], ".c")) {
            try sources.append(try std.fs.path.join(b.allocator, &.{ "lvgl", "src", path }));
        }
    }

    return sources;
}
